package com.b1.taskmanager.api;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import com.b1.taskmanager.parser.ContactXml;
import java.io.IOException;
import java.util.ListIterator;
import org.apache.log4j.Category;
import org.apache.log4j.Logger;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;

/**
 *  Реализация интерфейса ContactListInterface
 *
 */
public class ContactList implements ContactListInterface
{
    private static final Logger log = Logger.getLogger(ContactList.class);
    private List<Contact> contactList;

    public List<Contact> getContactList() 
    {
        return contactList;
    }

    public void setContactList(List<Contact> contactList) {
        this.contactList = contactList;
    }
    
    public ContactList() 
    {
        contactList = new ArrayList<Contact>();
        contactList = load();
        
    }
    public void addContactToList(Contact ct)
    {
        contactList.add(ct);
    }
    
    public String showContactList() // просмотр всех контактов какие у нас записаны в contactList
    {
        //System.out.println("id\tfirstName\tlastName+\thomePhone\tmobilePhone");
        StringBuffer str = new StringBuffer();
        for (int i = 0; i < contactList.size(); i++)
            //System.out.println(i+"\t"+contactList.get(i).showField());
            str.append(i+"\t"+contactList.get(i).showField()+"\n");
        return str.toString();
    }
    
    public Contact getContactByNumber(int id)
    {
        for (ListIterator<Contact> i = contactList.listIterator(); i.hasNext();) {
            Contact ct = i.next();
            if (ct.getId() == id) {
                return ct;
            }
        }
        log.info("No found contact");
        return null;   
    }
    @Override
    public void cahngeContact(int id,String firstName,String lastName,String phone)
    {
        for (ListIterator<Contact> i = contactList.listIterator(); i.hasNext();) {
            Contact ct = i.next();
            if (ct.getId() == id) 
            {
                ct.setFirstName(firstName);
                ct.setLastName(lastName);
                ct.setHomePhone(phone);
                save();
                break;
            }
        }
        
    }
    
    @Override
    public List<Contact> load()
    {
        try 
        {
            ContactXml contactFile = new ContactXml();
            String contactArray [][] = contactFile.getContactArray();
            Contact ct;
            for (int i = 0; i < contactArray.length; i++) 
            {
                ct = new Contact(Integer.parseInt(contactArray[i][0]),contactArray[i][1]);
                ct.setLastName(contactArray[i][2]);
                ct.setHomePhone(contactArray[i][3]);
                contactList.add(ct);
            }
           
        } 
        catch (IOException ex) 
        {
            log.debug(ContactList.class.getName(),ex);
            //Logger.getLogger(ContactList.class.getName()).log(Level.SEVERE, null, ex);
        } 
        catch (SAXException ex) 
        {
            log.debug(ContactList.class.getName(),ex);
            //Logger.getLogger(ContactList.class.getName()).log(Level.SEVERE, null, ex);
        } 
        catch (ParserConfigurationException ex) 
        {
            log.debug(ContactList.class.getName(),ex);
            //Logger.getLogger(ContactList.class.getName()).log(Level.SEVERE, null, ex);
        }
            return contactList;
    }
    
    @Override
    public void addContact(String firstName)
    {
        addContact(firstName,"","");
    }
    
    public void addContact(String firstName,String lastName,String homePhone)
    {
        Contact newContact = new Contact((int)System.currentTimeMillis(), firstName);
        newContact.setHomePhone(homePhone);
        newContact.setLastName(lastName);
        contactList.add(newContact);
        save();
    }
    
    @Override
    public boolean delContact(int id) 
    {
        //System.out.println(contactList.size());
        for (ListIterator<Contact> i = contactList.listIterator(); i.hasNext();) {
            Contact ct = i.next();
            if (ct.getId() == id) {
                i.remove();
                break;
            }
        }
        //System.out.println(contactList.size());
        save();
        return true;
    }
    
    public String[][] listToString()
    {
        String[][] s = new String[contactList.size()][4];
        for(int i = 0; i<contactList.size();i++)
        {
            Contact ct = contactList.listIterator(i).next();
            s[i][0] = String.valueOf(ct.getId());
            s[i][1] = ct.getFirstName();
            s[i][2] = ct.getLastName();
            s[i][3] = ct.getHomePhone();
        }
        return s;
    }
    
    public String listContactId()
    {
        String s="";
        for(int i = 0; i<contactList.size();i++)
        {
            Contact ct = contactList.listIterator(i).next();
            s+= String.valueOf(ct.getId())+" ";
        }
        return s;
        
    }
    
    @Override
    public boolean save()        //сохранение списка
    {
        ContactXml cx;
        try 
        {
            cx = new ContactXml();
            cx.writeXml(listToString());
        } 
        catch (IOException ex) 
        {
            log.debug(ContactList.class.getName(),ex);
            //Logger.getLogger(ContactList.class.getName()).log(Level.SEVERE, null, ex);
        } 
        catch (SAXException ex) 
        {
            log.debug(ContactList.class.getName(),ex);
            //Logger.getLogger(ContactList.class.getName()).log(Level.SEVERE, null, ex);
        } 
        catch (ParserConfigurationException ex) 
        {
            log.debug(ContactList.class.getName(),ex);
            //Logger.getLogger(ContactList.class.getName()).log(Level.SEVERE, null, ex);
        }
        return true;
    } 
}
